package com.medical.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.medical.config.AlipayConfig;
import com.medical.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public String createOrder(String orderNo, String totalAmount, String subject) throws AlipayApiException {
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        request.setReturnUrl(alipayConfig.getReturnUrl());

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("total_amount", totalAmount);
        bizContent.put("subject", subject);
        bizContent.put("product_code", "QUICK_WAP_WAY");

        request.setBizContent(bizContent.toString());

        try {
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
            if(response.isSuccess()){
                return response.getBody();
            } else {
                throw new RuntimeException("创建支付订单失败: " + response.getMsg());
            }
        } catch (AlipayApiException e) {
            log.error("支付宝接口调用失败", e);
            throw e;
        }
    }

    @Override
    public boolean verifyNotify(Map<String, String> params) throws AlipayApiException {
        return false;
    }
}
